package server;

import demacia.Context;
import demacia.Mapper;
import demacia.Wrapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

/**
 * @program: minicat
 * @description
 * @author: luffy
 * @create: 2020-08-03 11:25
 */
public class RequestProcessor extends Thread {
    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.mapper = mapper;
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            String url = request.getUrl();
            if (mapper != null) {
                //获取context
                List<Context> contextList = mapper.getHostList().get(0).getContextList();
                String appUrl = url.substring(0, url.indexOf("/", url.indexOf("/") + 1));
                for (Context context : contextList) {
                    if (context.getName().equalsIgnoreCase(appUrl)) {
                        String wrapperUrl = url.substring(url.indexOf("/", url.indexOf("/") + 1));
                        for (Wrapper wrapper : context.getWrapperList()) {
                            if (wrapper.getUrl().equalsIgnoreCase(wrapperUrl)) {
                                wrapper.getHttpServlet().service(request,response);
                            }
                        }
                    }
                }
            }
            socket.close();
        } catch (Exception e
        ) {
            e.printStackTrace();
        }

    }
}
